﻿package wibrst.net {
	import com.adobe.serialization.json.JSON;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import wibrst.utils.DevUtil;
	import wibrst.utils.StringUtil;
	/**
	 * ...
	 * @author wibrst@qq.com
	 */
	public class SignalCenter extends DataReqCenter{
		
		static public const ID_DATA_CONFIG:String = "ID_DATA_CONFIG";
		
		static private var _i:SignalCenter;
		
		static public function get i():SignalCenter {
			return _i ||=  new SignalCenter;
		}
		
		public function sendReq (
				sIdSignal:String, oDataPost:Object = null, uLoad:String = "",
				dataFormat:String = URLLoaderDataFormat.TEXT,
				bTraceDetail:Boolean = false, bAvoidCache:Boolean = true
		):void {
			
			this._oDictOK[ sIdSignal ] = false;
			
			if ( uLoad == "" ) uLoad = this.queryPath( sIdSignal );
			
			if ( bAvoidCache ) {
				var sStampAvoidCache:String = new Date().getTime().toString();
				uLoad += ( uLoad.indexOf("?") == -1 ? "?stamp=" : "&stamp=" ) + sStampAvoidCache;
			}
			
			var sTraceData:String = oDataPost ? StringUtil.getBrief( DevUtil.viewThru( oDataPost ), 100, 100 ) : "";
			trace( this, "sendReq -->: <" +sIdSignal+ ">", uLoad, sTraceData );
			var uldr:MarkedURLLoader = new MarkedURLLoader( sIdSignal );
			uldr.addEventListener( Event.COMPLETE, urlDataHandler );
			uldr.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
			uldr.dataFormat = dataFormat;
			
			var ur:URLRequest = new URLRequest( uLoad );
			ur.method = URLRequestMethod.POST;
			ur.contentType = "application/json";
			
			if ( oDataPost != null) {
				var data:Object = /*CommUtils.urlencodeGB2312(*/ JSON.encode(oDataPost) /*)*/;
				if ( bTraceDetail ) trace( this, "sendReq --> data:\n" + data );
				ur.data = data;
				//trace( this, "signalHandler JSON.encode(oDataPost):", ur.data );
			}
			uldr.load( ur );
		}
		
		private function ioErrorHandler( evt:IOErrorEvent ):void {
			var uldr:MarkedURLLoader = evt.currentTarget as MarkedURLLoader;
			
			trace( this, "ioErrorHandler:", evt );
			dispatchEvent( new ESignal( ESignal.IO_ERROR, uldr.sId, uldr.data ) );
		}
		
		private function urlDataHandler( evt:Event ):void {
			var uldr:MarkedURLLoader = evt.currentTarget as MarkedURLLoader;
			
			switch( evt.type ) {
			case Event.COMPLETE:		// -+- -+- -+- -+- -+- -+- -+- -+- -+- -+- -+- -+-
				this._oDictOK[ uldr.sId ] = true;
				
				trace( this, "urlDataHandler <--: <" +uldr.sId + ">" );
				if ( this._bTraceDetailRec ) trace( this, "urlDataHandler <-- detail:\n" + uldr.data );
				
				super.dispatchEvent( new ESignal( ESignal.ALL_READY, uldr.sId, uldr.data ) );
				
			break;
			}
		}
		
	}

}